package com.dxg.msns.music.service.impl;

import com.dxg.msns.music.mapper.PlaylistFavoriteMapper;
import com.dxg.msns.music.mapper.PlaylistMapper;
import com.dxg.msns.music.pojo.Playlist;
import com.dxg.msns.music.pojo.PlaylistFavorite;
import com.dxg.msns.music.service.PlaylistFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PlaylistFavoriteServiceImpl implements PlaylistFavoriteService {

    @Autowired
    private PlaylistFavoriteMapper favoriteMapper;
    @Autowired
    private PlaylistMapper playlistMapper;
    public boolean favoritePlaylist(String userId, String playlistId) {
        PlaylistFavorite existing = favoriteMapper.selectByUserAndPlaylist(userId, playlistId);
        if (existing == null) {
            PlaylistFavorite newFavorite = new PlaylistFavorite();
            newFavorite.setUserId(userId);
            newFavorite.setPlaylistId(playlistId);
            newFavorite.setCreateTime(new Date());
            newFavorite.setStatus(0); // 收藏
            return favoriteMapper.insert(newFavorite) > 0;
        } else {
            // 已存在但可能是取消状态
            return favoriteMapper.updateStatus(userId, playlistId, 0) > 0;
        }
    }

    public boolean unfavoritePlaylist(String userId, String playlistId) {
        return favoriteMapper.updateStatus(userId, playlistId, 1) > 0;
    }

    public List<Playlist> getFavoritePlaylistIds(String userId) {
        List<String> listIds=favoriteMapper.selectPlaylistIdsByUser(userId);
        List<Playlist> playlists = new ArrayList<>();
        for (String listId : listIds){
            if (listId != null)
                playlists.add(playlistMapper.selectById(listId));

        }
        return playlists;
    }

    public boolean isFavorited(String userId, String playlistId) {
        PlaylistFavorite pf = favoriteMapper.selectByUserAndPlaylist(userId, playlistId);
        return pf != null && pf.getStatus() == 0;
    }
}
